<template>
  <view class="container">
    <!-- Header -->
    <view class="header">
      <view class="header-content">
        <view class="title">速判练习</view>
        <progress-bar
            :current-step="completedConnections"
            :show-info="true"
            :total-steps="questionData.fractions.length"
            label="连线进度"
        ></progress-bar>
      </view>
    </view>

    <!-- Practice Area -->
    <view v-if="questionData" class="practice-area">
      <!-- Fractions Column -->
      <view class="fractions-column">
        <view class="column-title">分数</view>
        <view
            v-for="fraction in questionData.fractions"
            :key="fraction.id"
            :class="{
                        'connected': isConnected(fraction.id),
                        'selected': selectedFraction === fraction.id
                    }"
            class="fraction-item"
            @tap="selectFraction(fraction.id)"
        >
          {{ fraction.display }}
        </view>
      </view>

      <!-- Connection Area -->
      <view class="connection-area">
        <view class="connections-list">
          <view
              v-for="(connection, index) in userConnections"
              :key="index"
              class="connection-item"
              @tap="removeConnection(index)"
          >
            <text class="connection-text">
              {{ getFractionDisplay(connection.fractionId) }} = {{ getDecimalDisplay(connection.decimalId) }}
            </text>
            <uni-icons color="#ff6b6b" size="16" type="closeempty"></uni-icons>
          </view>
        </view>
      </view>

      <!-- Decimals Column -->
      <view class="decimals-column">
        <view class="column-title">小数</view>
        <view
            v-for="decimal in questionData.decimals"
            :key="decimal.id"
            :class="{
                        'connected': isConnected(decimal.id, 'decimal'),
                        'selected': selectedDecimal === decimal.id
                    }"
            class="decimal-item"
            @tap="selectDecimal(decimal.id)"
        >
          {{ decimal.display }}
        </view>
      </view>
    </view>

    <!-- Control Buttons -->
    <view class="controls">
      <button class="control-btn reset-btn" @tap="resetConnections">
        <uni-icons color="#666" size="20" type="refresh"></uni-icons>
        <text>重置</text>
      </button>
      <button
          :class="{ 'disabled': !canSubmit }"
          :disabled="!canSubmit"
          class="control-btn submit-btn"
          @tap="submitAnswers"
      >
        <uni-icons color="#ffffff" size="20" type="checkmarkempty"></uni-icons>
        <text>提交答案</text>
      </button>
    </view>
  </view>
</template>

<script>
import SpeedJudgeGenerator from '@/utils/question-generator/question-generator-speed-judge.js';
import ProgressBar from '@/components/common/progress-bar.vue';

export default {
  components: {
    ProgressBar
  },
  data() {
    return {
      questionData: null,
      userConnections: [],
      selectedFraction: null,
      selectedDecimal: null,
      startTime: 0
    }
  },
  computed: {
    completedConnections() {
      return this.userConnections.length;
    },
    canSubmit() {
      return this.questionData &&
          this.userConnections.length === this.questionData.fractions.length;
    }
  },
  onLoad(options) {
    const count = parseInt(options.count) || 5;
    this.startTime = Date.now();
    this.generateQuestions(count);
  },
  methods: {
    // 生成题目
    generateQuestions(count) {
      this.questionData = SpeedJudgeGenerator.generateQuestions(count);
    },

    // 选择分数
    selectFraction(fractionId) {
      if (this.selectedFraction === fractionId) {
        // 取消选择
        this.selectedFraction = null;
        return;
      }

      this.selectedFraction = fractionId;

      // 如果已经选择了小数，则创建连接
      if (this.selectedDecimal) {
        this.createConnection(this.selectedFraction, this.selectedDecimal);
        this.selectedFraction = null;
        this.selectedDecimal = null;
      }
    },

    // 选择小数
    selectDecimal(decimalId) {
      if (this.selectedDecimal === decimalId) {
        // 取消选择
        this.selectedDecimal = null;
        return;
      }

      this.selectedDecimal = decimalId;

      // 如果已经选择了分数，则创建连接
      if (this.selectedFraction) {
        this.createConnection(this.selectedFraction, this.selectedDecimal);
        this.selectedFraction = null;
        this.selectedDecimal = null;
      }
    },

    // 创建连接
    createConnection(fractionId, decimalId) {
      // 检查是否已经存在连接
      const existingConnectionIndex = this.userConnections.findIndex(
          conn => conn.fractionId === fractionId || conn.decimalId === decimalId
      );

      if (existingConnectionIndex !== -1) {
        // 移除已存在的连接
        this.userConnections.splice(existingConnectionIndex, 1);
      }

      // 添加新连接
      this.userConnections.push({
        fractionId,
        decimalId
      });
    },

    // 移除连接
    removeConnection(index) {
      this.userConnections.splice(index, 1);
      uni.showToast({
        title: '已取消连接',
        icon: 'none',
        duration: 1000
      });
    },

    // 获取分数显示
    getFractionDisplay(fractionId) {
      const fraction = this.questionData.fractions.find(f => f.id === fractionId);
      return fraction ? fraction.display : '';
    },

    // 获取小数显示
    getDecimalDisplay(decimalId) {
      const decimal = this.questionData.decimals.find(d => d.id === decimalId);
      return decimal ? decimal.display : '';
    },

    // 获取元素位置
    getElementPosition(id, type) {
      // 简化的位置计算，实际应该获取元素的真实位置
      return {x: type === 'fraction' ? 100 : 275, y: 100};
    },

    // 检查是否已连接
    isConnected(id, type = 'fraction') {
      if (type === 'fraction') {
        return this.userConnections.some(conn => conn.fractionId === id);
      } else {
        return this.userConnections.some(conn => conn.decimalId === id);
      }
    },

    // 重置连接
    resetConnections() {
      this.userConnections = [];
      this.selectedFraction = null;
      this.selectedDecimal = null;
      uni.showToast({
        title: '已重置所有连接',
        icon: 'none'
      });
    },

    // 提交答案
    submitAnswers() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完成所有连线',
          icon: 'none'
        });
        return;
      }

      const answers = this.userConnections.map(conn => ({
        fractionId: conn.fractionId,
        decimalId: conn.decimalId
      }));

      // 跳转到结果页面
      uni.navigateTo({
        url: `/pages/speed-judge/result`,
        success: () => {
          // 通过全局数据传递答题结果
          getApp().globalData.speedJudgeResult = {
            questionData: this.questionData,
            userAnswers: answers,
            startTime: this.startTime,
            endTime: Date.now()
          };
        }
      });
    }
  },
  onReady() {
    // 确保startTime已初始化
    if (!this.startTime) {
      this.startTime = Date.now();
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  padding: 20rpx 40rpx 30rpx;
  color: white;

  .header-content {
    .title {
      font-size: 36rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 20rpx;
    }
  }
}

.practice-area {
  flex: 1;
  display: flex;
  padding: 30rpx 20rpx;
  position: relative;
}

.fractions-column,
.decimals-column {
  width: 25%;

  .column-title {
    font-size: 28rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
    color: #333;
  }
}

.fraction-item,
.decimal-item {
  background: white;
  padding: 25rpx 15rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.1);
  border: 3rpx solid transparent;
  transition: all 0.3s ease;

  &.connected {
    border-color: #007AFF;
    background-color: #e7f3ff;
  }

  &.selected {
    border-color: #ff6b6b;
    background-color: #ffe6e6;
    transform: scale(1.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

.connection-area {
  flex: 1;
  padding: 20rpx;
  margin: 0 20rpx;
  background: white;
  border-radius: 15rpx;
  box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.1);

  .connections-list {
    .connection-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx;
      margin-bottom: 15rpx;
      background: linear-gradient(135deg, #f0fdff, #e0f8ff);
      border-radius: 10rpx;
      border: 2rpx solid #007AFF;

      .connection-text {
        font-size: 28rpx;
        font-weight: bold;
        color: #007AFF;
      }

      &:active {
        background: linear-gradient(135deg, #ffeaea, #ffcccc);
        border-color: #ff6b6b;
      }
    }
  }
}

.controls {
  display: flex;
  padding: 30rpx 40rpx;
  gap: 20rpx;
  background: white;
  box-shadow: 0 -3rpx 10rpx rgba(0, 0, 0, 0.1);
}

.control-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;

  &.reset-btn {
    background-color: #f8f9fa;
    color: #666;
    border: 2rpx solid #dee2e6;
  }

  &.submit-btn {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;

    &.disabled {
      background: #6c757d;
      opacity: 0.6;
    }
  }

  &:active:not(.disabled) {
    transform: scale(0.98);
  }
}
</style>